<?php


namespace app\services;


use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;

class Order
{


    /**
     * 订单信息
     * @param $order
     * @param $address_id
     * @param $province
     * @param $user_id
     * @param int $type
     * @param int $channel_type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function OrderArray($order, $address_id, $province, $user_id, $type = 2, $channel_type = 1)
    {
        $msg = array();
        foreach ($order as $v) {
            $msg[$v['goods_spec_id']] = $v['msg'];
        }
        $ids = array_column($order, 'goods_spec_id');
        if ($type == 2) {
            $cart_list = \app\services\Cart::getInstance()->cartList($user_id);
        } else {
            $cart_list[$order[0]['goods_spec_id']] = $order[0]['num'];
        }
        $result = Db::name('commodity_spec')
            ->field('a.goods_spec_id,a.spec_ids,a.spec_text,a.goods_id,c.name as merchant_name,b.m_id,b.m_id as merchant_id,b.name as goods_name,spec_text,a.picture,a.price,b.sn as goods_sn,b.image as goods_img,b.express_id,b.channel')
            ->alias('a')
            ->leftJoin('commodity_goods b', 'a.goods_id = b.id')
            ->leftJoin('merchant c', 'b.m_id = c.id')
            ->whereIn('a.goods_spec_id', $ids)
            ->select()
            ->toArray();
        $postfee = 0;
        $area_discern_id = '';
        if (!empty($result)) {
            //根据不同商家组装数据
            foreach ($result as $key => &$value) {
                if ($value['channel'] == 1 && $channel_type == 2) {
                    throw new HttpException(500,'下单失败！channel');
                }
                if ($value['channel'] == 2 && $channel_type == 1) {
                    throw new HttpException(500,'下单失败！channel');
                }
//                $result[$key] = $value['goods_spec_id'];
                $value['num'] = $cart_list[$value['goods_spec_id']];
                $value['postfee'] = 0;
                $value['is_area_discern'] = 0;
                //计算商品是否有加价地区
                //计算商品是否包邮
                $delivery = Db::name('commodity_express_delivery')->where(['id' => $value['express_id']])->find();
                $area_discern = explode(',', $delivery['shipping_address']);
                if (in_array($province, $area_discern)) {
                    $value['is_area_discern'] = 1;
                }
                $markup = Db::name('commodity_express_markup')->where(['d_id' => $value['express_id']])->select()->toArray();
                $markup = array_column($markup, null, 'area_text');
                if (array_key_exists($province, $markup)) {
                    $value['postfee'] = $markup[$province]['area_price'];
                    $postfee += $value['postfee'] * $value['num'];
                }
                $value['goods_num'] = $value['num'];
                $value['goods_price'] = $value['price'];
                $value['total'] = ($value['goods_price'] * $value['num']) + ($value['postfee'] * $value['num']);
                $value['order_sn'] = createdOrderSn();
                $value['user_id'] = $user_id;
                $value['address_id'] = $address_id;
                $value['buyer_msg'] = $msg[$value['goods_spec_id']];
                if ($channel_type == 2) {
                    $value['status'] = 10;
                }
            }

        }
        $total_price = array_sum(array_column($result, 'total'));
        return ['total_price' => $total_price, 'postFee' => $postfee, 'list' => $result, 'area_discern_id' => $area_discern_id];
    }


    /**
     * 秒杀状态
     * @param $user_id
     * @param $goods_number_key
     * @param $user_queue_key
     * @param $pike
     * @return array
     */
    public static function SpikeStatus($user_id, $goods_number_key, $user_queue_key, $pike)
    {
        try {
            $redis = Cache::store('redis');
            $gnRedis = $redis->llen("$goods_number_key");
            if (!$gnRedis || $gnRedis == 0) {
                return ['code' => 0, 'msg' => '系统繁忙，请稍后抢购1！'];
            }
            if (!$redis->hGet("$user_queue_key", $user_id)) {
                $redis->lpop("$goods_number_key");
            } else {
                return ['code' => 0, 'msg' => '您已完成抢购'];
            }
            if (!$redis->hGet("$user_queue_key", $user_id)) {
                $userinfo = array(
                    "user_id" => $user_id,
                    "created_time" => time()
                );
                $redis->hSet("$user_queue_key", $user_id, serialize($userinfo));
                return ['code' => 1, 'msg' => '成功'];
            } else {
                return ['code' => 0, 'msg' => '您已完成抢购'];
            }

        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '系统繁忙，请稍后抢购3！'];
        }
    }
}